package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    MinioConstantProperties minioConstantProperties;

    @Override
    public String fileUpload(MultipartFile file)throws Exception {

        String url = "";
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioConstantProperties.getEndpointUrl())
                .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                .build();

        // 判断桶是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());

        if(!found){
            // 如果不存在，则创建
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        }else {
            //桶已存在
            System.out.println("Bucket"+minioConstantProperties.getBucketName()+"已存在");
        }
        //  生成文件名。
        String fileName = UUID.randomUUID().toString().replaceAll("-","")+"_"+ FilenameUtils.getExtension(file.getOriginalFilename());
        //  调用上传方法.
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioConstantProperties.getBucketName()).object(fileName).stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build()
        );
        //  拼接url
        url = minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+fileName;

        return url;
    }
}
